package com.elastic.test.high_level_client;

import org.apache.http.Header;
import org.apache.http.HttpHost;
import org.apache.http.message.BasicHeader;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.sniff.Sniffer;
import org.elasticsearch.client.sniff.SnifferBuilder;

import java.io.IOException;

/**
 * @author: 李德才
 * @description:
 * @create: 2021-04-11 11:43
 **/
public class ESClient {
    private static ESClient esClient;
    private static String host = "192.168.31.100:9200";
    private RestClientBuilder builder;
    private static Sniffer sniffer;
    private static RestHighLevelClient highLevelClient;

    private ESClient() {

    }

    public static ESClient getInstance() {
        if (esClient == null) {
            synchronized (ESClient.class) {
                if (esClient == null) {
                    esClient = new ESClient();
                }
            }
        }
        return esClient;
    }

    public void closeClient() {
        try {
            sniffer.close();
            highLevelClient.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public RestClientBuilder initBuilder() {
        String[] hosts = host.split(",");
        HttpHost[] httpHosts = new HttpHost[hosts.length];
        for (int i = 0; i < hosts.length; i++) {
            String[] host = hosts[i].split(":");
            httpHosts[i] = new HttpHost(host[0], Integer.parseInt(host[1]), "http");
        }
        builder = RestClient.builder(httpHosts);
        Header[] headers = new Header[]{new BasicHeader("header", "application/json")};
        builder.setDefaultHeaders(headers);
        return builder;
    }


    public RestHighLevelClient getHighLevelClient() {
        if (highLevelClient == null) {
            synchronized (ESClient.class) {
                if (highLevelClient == null) {
                    highLevelClient = new RestHighLevelClient(initBuilder());
                    RestClient lowLevelClient = highLevelClient.getLowLevelClient();
                    SnifferBuilder builder = Sniffer.builder(lowLevelClient);
                    sniffer = builder.setSniffAfterFailureDelayMillis(5000).setSniffAfterFailureDelayMillis(15000).build();
                }
            }
        }
        return highLevelClient;
    }
}
